#!/usr/bin/env python
#
# Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import re
import sys

def example_regex():
  """Return a regex that matches a README's example stanza."""
  pattern = '<!--<div class="material-code-render" markdown="1">-->(.*?)<!--</div>-->'
  return re.compile(pattern, re.MULTILINE | re.DOTALL)


def language_regex(language):
  """Return a regex that matches a code stanza in a particular language."""
  pattern = '~~~\s+%s(.*?)~~~' % language
  return re.compile(pattern, re.MULTILINE | re.DOTALL)


def delete_matching(s, regex):
  """Return the input string with substrings matching regex deleted."""
  result = ""
  index = 0
  for i in regex.finditer(s):
    result += s[index:i.start(0)]
    index = i.end(0)
  result += s[index:]
  return result


def main():
  # Private components aren't required to have examples.
  if 'private/' in sys.argv[1]:
    return

  example_matcher = example_regex()
  objc_matcher = language_regex('objc')
  swift_matcher = language_regex('swift')

  readme = os.path.join(sys.argv[1], 'README.md')
  with open(readme) as f:
    contents = f.read()

  # Check each example stanza has both languages.
  for i in example_matcher.finditer(contents):
    example = i.group(1)
    objcMatch = objc_matcher.search(example)
    swiftMatch = swift_matcher.search(example)
    if not (objcMatch and swiftMatch):
      print ("Error: '%s' contains an example that is missing Objective-C or "
             "Swift code.") % readme
      sys.exit(-1)

    # Check each pair of examples has swift before objc.
    elif not (swiftMatch.start() < objcMatch.start()):
      print ("Error: '{}' has an Objc example before a Swift "
             "example:\n{}".format(readme, example))
      sys.exit(-1)

  # Check that no example code appears outside of an example stanza.
  outside = delete_matching(contents, example_matcher)
  if objc_matcher.search(outside) or swift_matcher.search(outside):
    print ("Error: '%s' contains example code outside of a "
           "'material-code-render' section.") % readme
    sys.exit(-1)


if __name__ == '__main__':
  main()
